<?PHP

namespace app\util\rke;

class Tool
{
    private static $method;

    public static $card_type = [
        '0' => 'Card', // 刷卡数据
        '1' => 'RS232', // 二维码
        '2' => 'Password',  // 密码器
        '3' => '按钮请求',
        '6' => '二代证数据',
        '9' => 'Base64 Qrcode', // Base64二维码,使用一次后失效
        '10' => '指纹数据',
        '11' => '指静脉数据',
        '12' => 'RFID卡',
        '13' => '人脸',
    ];

    //设置Method 【get/post...】
    public static function SetMethod($str)
    {
        self::$method = $str;
    }

    //判断是否以什么开头
    static function startsWith(string $string, string $subString): bool
    {
//        echo 'A:'.substr($string, 0, strlen($subString));
//        echo 'B:'.$subString;
//        return substr($string, 0, strlen($subString)) === $subString;
        return strpos($string, $subString) > 0;
    }

    //Post时，获取需要josn格式数据
    static function GetPostArray()
    {
        $rawPost = file_get_contents('php://input');
        return json_decode($rawPost,true);
    }

    /**
     * 应答拼接
     * @param int $AcsRes 可选参数，0拒绝，1打开，2报警，3关闭
     * @param int $ActIndex 可选参数，动作位置，继电器位置, 0-2
     * @param int $Time 可选参数，继电器动作时间,也就是继电器保持动作多少秒。
     * @param string $Card 可选参数，卡号字符串，显示在LCD屏幕上,小于16字节
     * @param array $voice 应答-显示语音
            $voice = [
            'Name'      =>  '',                 //可选参数，姓名，显示在LCD屏幕上,小于16字节
            'Note'      =>  $Note . "服务器应答",//可选参数，事件说明，显示在LCD屏幕上,小于32字节
            'Systime'   =>  date('Y-m-d H:i:s'),//可选参数，时间，显示在LCD屏幕上，小于20字节
            'Voice'     =>  '测试语音',          //可选参数，语音字符串，用于播报，小于，小于40字节
            ];
     * @return array
     */
    static function GetAnswer($AcsRes = 0, $ActIndex = 1, $Time = 1, $Card = '', $voice = []): array
    {
        $date = array();
        strlen($ActIndex) > 0 ? $date['ActIndex'] = $ActIndex : "";
        strlen($AcsRes) > 0 ? $date['AcsRes'] = $AcsRes : "";
        strlen($Time) > 0 ? $date['Time'] = $Time : "";
        strlen($Card) > 0 ? $date['Card'] = $Card : "";
        if (!empty($voice)) {
            foreach ($voice as $k => $v) {
                strlen($v) > 0 ? $date[$k] = $v : "";
            }
        }
        return $date;
    }

    //获取身份证信息
    static function GetInfoByChinacard($jsonDate): array
    {
        $ChinaCard = [
            'Card' => $jsonDate->Card,
            'Name' => self::ByteArrayToString(self::Chang(self::GetBytes_16($jsonDate->Name))),
            'Bthday' => self::FormatDate($jsonDate->Bthday),
            'Sex' => $jsonDate->Sex == '1' ? '男' : '女',
            'Dept' => self::ByteArrayToString(self::Chang(self::GetBytes_16($jsonDate->Dept))),
            'DateFrm' => self::FormatDate($jsonDate->DateFrm),
            'DateTo' => self::FormatDate($jsonDate->DateTo),
            'Nation' => self::GetNation($jsonDate->Nation),
            'Addr' => self::ByteArrayToString(self::Chang(self::GetBytes_16($jsonDate->Addr))),
        ];
        if ($jsonDate->Photo) {
            self::GetPhoto('E:/web/phpTest/tmp', $jsonDate->Photo);
        }
        return $ChinaCard;
    }

    //照片处理
    private static function GetPhoto($savePath, $base64_img)
    {
        $imageDate = self::DecodeBase64($base64_img);
        $imageName = date("YmdHis", time()) . "_" . rand(1001, 9999) . '.wlt';
        is_dir($savePath) or mkdir($savePath, 0755, true);
        $imageSrc = $savePath . "/" . $imageName;

        $f = fopen($imageSrc, "w");
        fwrite($f, $imageDate);
        fclose($f);
    }

    private static function DecodeBase64($base64_img)
    {
        if (self::$method === "POST") {
            //POST的数据时PHP默认将+转换成了_；而GET来的数据php未做转换。
            $base64_img = str_replace('_', "+", $base64_img);
        }
        $base64_img = str_replace(' ', "+", $base64_img);
        $base64_img = str_replace('-', "+", $base64_img);
        $base64_img = str_replace('_', "/", $base64_img);

        $len = strlen($base64_img) % 4;
        if ($len == 2) {
            $base64_img .= "==";
        }
        if ($len == 3) {
            $base64_img .= "=";
        }
        echo $base64_img;
        return base64_decode($base64_img);
    }

    //格式化日期时间
    private static function FormatDate($strTime)
    {
        return substr($strTime, 0, 4) . '.' . substr($strTime, 4, 2) . '.' . substr($strTime, 6, 2);
    }

    //获取民族
    private static function GetNation($id): string
    {
        $nationality = [
            "汉", "蒙古", "回", "藏", "维吾尔", "苗", "彝", "壮", "布依", "朝鲜",
            "满", "侗", "瑶", "白", "土家", "哈尼", "哈萨克", "傣", "黎", "傈僳", "佤", "畲", "高山",
            "拉祜", "水", "东乡", "纳西", "景颇", "柯尔克孜", "土", "达斡尔", "仫佬", "羌", "布朗",
            "撒拉", "毛南", "仡佬", "锡伯", "阿昌", "普米", "塔吉克", "怒", "乌孜别克", "俄罗斯", "鄂温克",
            "德昂", "保安", "裕固", "京", "塔塔尔", "独龙", "鄂伦春", "赫哲", "门巴", "珞巴", "基诺"
        ];
        if ($id > 0) {
            --$id;
        }
        return $nationality[$id];
    }

    //获取16进制字符串
    private static function GetBytes_16($str): array
    {
        $len = strlen($str);
        if (($len % 2) != 0) {
            $str .= "0";
        }
        $bytes = array();
        for ($i = 0; $i < $len / 2; $i++) {
            $bytes[] = hexdec(substr($str, $i * 2, 2));
        }
        return $bytes;
    }

    //数组两两交换位置
    private static function Chang($arr): array
    {
        $date = array();
        for ($i = 0, $j = 0; $i < count($arr) / 2; $i++, $j = $j + 2) {
            $temp = $arr[$j];
            $date[$j] = $arr[$j + 1];
            $date[$j + 1] = $temp;
        }
        return $date;
    }

    //str转字节数组【此方法没有使用-备用】
    private static function StringToByteArray($str): array
    {
        $str = iconv('UTF-8', 'UTF-16', $str);
        preg_match_all('/(.)/s', $str, $bytes);
        $bytes = array_map('ord', $bytes[1]);
        return $bytes;
    }

    //字节数组转str
    private static function ByteArrayToString($bytes)
    {
        $bytes = array_map('chr', $bytes);
        $str = implode('', $bytes);
        $str = iconv('UTF-16', 'UTF-8', $str);
        return $str;
    }
}
